package com.payment.system.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.payment.common.base.AjaxResult;
import com.payment.common.utils.StringUtils;
import com.payment.system.domain.Merchant;
import com.payment.system.domain.PaymentOrder;
import com.payment.system.mapper.MerchantMapper;
import com.payment.system.mapper.PaymentOrderMapper;
import com.payment.system.service.ICardEvaluateService;
import com.payment.system.util.GuangGuUtil;
import com.payment.system.vo.CardEvaluateSendSmsVo;
import com.payment.system.vo.CardEvaluateVo;

/**
 * @author fuzhili
 * @Description:
 * @date 2019/11/22 11:46
 */
@Service
public class CardEvaluateServiceImpl implements ICardEvaluateService {
	private static final Logger LOGGER = LoggerFactory.getLogger(CardEvaluateServiceImpl.class);

	@Autowired
	private MerchantMapper merchantMapper;
	@Autowired
	private PaymentOrderMapper paymentOrderMapper;

	/**
	 * 卡测评获取验证码
	 *
	 * @param merId
	 * @param bankCardNo
	 * @param name
	 * @param userIdCard
	 * @param bankCardPhone
	 * @return
	 */
	@Override
	public AjaxResult sendSms(String merId, String bankCardNo, String name, String userIdCard, String bankCardPhone) {
		if (StringUtils.isEmpty(merId) || StringUtils.isEmpty(bankCardNo) || StringUtils.isEmpty(name)
				|| StringUtils.isEmpty(userIdCard) || StringUtils.isEmpty(bankCardPhone)) {
			return AjaxResult.error(1, "缺失必要参数");
		}
		Merchant merchant = merchantMapper.selectMerchantById(merId);
		if (merchant == null || StringUtils.isEmpty(merchant.getAcqMerchantNo())) {
			return AjaxResult.error(2, "用户不存在或未签约通道");
		}
		// 订单处理，
		String orderNo = StringUtils.createNum();
		CardEvaluateSendSmsVo cardEvaluateSendSmsVo = new CardEvaluateSendSmsVo();
		cardEvaluateSendSmsVo.setBankCardNo(bankCardNo);
		cardEvaluateSendSmsVo.setName(name);
		cardEvaluateSendSmsVo.setUserIdCard(userIdCard);
		cardEvaluateSendSmsVo.setBankCardPhone(bankCardPhone);
		cardEvaluateSendSmsVo.setUserId(merchant.getAcqMerchantNo());
		cardEvaluateSendSmsVo.setSeriaNo(orderNo);
		try {
			JSONObject jsonObject = GuangGuUtil.cardEvaluateSendSms(cardEvaluateSendSmsVo);
			if (jsonObject == null) {
				return AjaxResult.error(3, "验证码发送失败，请重试！");
			}
			String resCode = jsonObject.getString("res_code");
			if (("YQB000000").equals(resCode)) {
				Map<String, String> map = new HashMap<>(4);
				map.put("serialNumber", jsonObject.getString("serialNumber"));
				map.put("seriaNo", cardEvaluateSendSmsVo.getSeriaNo());
				return AjaxResult.successAndData("发送验证码成功", map);
			} else {
				LOGGER.error("【卡测评发送验证码】{}", jsonObject.getString("res_msg"));
				return AjaxResult.error(1, jsonObject.getString("res_msg"));

			}
		} catch (Exception e) {
			LOGGER.error("【卡测评发送验证码异常】{}", e);
			return AjaxResult.error(1, "卡测评发送验证码异常");
		}

	}

	/**
	 * 确认验证码
	 *
	 * @return
	 */
	@Override
	public AjaxResult smsConfirm(String seriaNo, String identifyingCode, String serialNumber) {
		if (StringUtils.isEmpty(seriaNo) || StringUtils.isEmpty(identifyingCode) || StringUtils.isEmpty(serialNumber)) {
			return AjaxResult.error(1, "缺失必要参数");
		}
		CardEvaluateSendSmsVo cardEvaluateSendSmsVo = new CardEvaluateSendSmsVo();
		cardEvaluateSendSmsVo.setSeriaNo(seriaNo);
		cardEvaluateSendSmsVo.setSerialNumber(serialNumber);
		cardEvaluateSendSmsVo.setIdentifyingCode(identifyingCode);
		try {
			JSONObject jsonObject = GuangGuUtil.cardEvaluateSendSmsConfirm(cardEvaluateSendSmsVo);
			if (jsonObject == null) {
				return AjaxResult.error(3, "确认验证码，请重试！");
			}
			String resCode = jsonObject.getString("res_code");
			if (("YQB000000").equals(resCode)) {
				return AjaxResult.success("成功");
			} else {
				LOGGER.error("【卡测评发送验证码】{}", jsonObject.getString("res_msg"));
				return AjaxResult.error(1, jsonObject.getString("res_msg"));
			}
		} catch (Exception e) {
			LOGGER.error("【卡测评确认验证码异常】{}", e);
			return AjaxResult.error(1, "卡测评确认验证码异常");
		}
	}

	/**
	 * 下单 返回H5卡测评链接
	 */
	@Override
	public AjaxResult placeOrder(String orderId, String bankCardNo, String name, String userIdCard,
			String bankCardPhone, String identifyingCode, String serialNumber) {
		if (StringUtils.isEmpty(orderId)) {
			return AjaxResult.error(1, "缺失必要参数");
		}
		PaymentOrder order = paymentOrderMapper.selectPaymentOrderById(orderId);
		if (order == null || !order.getOrderStatus().equals(1)) {
			return AjaxResult.error(2, "您尚未充值成功,请先充值");
		}
		Merchant merchant = merchantMapper.selectMerchantById(order.getMerchantId());
		if (merchant == null || StringUtils.isEmpty(merchant.getAcqMerchantNo())) {
			return AjaxResult.error(2, "用户不存在或未签约通道");
		}
		CardEvaluateSendSmsVo cardEvaluateSendSmsVo = new CardEvaluateSendSmsVo();
		cardEvaluateSendSmsVo.setIdentifyingCode(identifyingCode);
		cardEvaluateSendSmsVo.setSerialNumber(serialNumber);
		cardEvaluateSendSmsVo.setSeriaNo(order.getOrderNo());
		cardEvaluateSendSmsVo.setBankCardNo(bankCardNo);
		cardEvaluateSendSmsVo.setBankCardPhone(bankCardPhone);
		cardEvaluateSendSmsVo.setName(name);
		cardEvaluateSendSmsVo.setUserIdCard(userIdCard);
		cardEvaluateSendSmsVo.setUserId(merchant.getAcqMerchantNo());
		try {
			JSONObject jsonObject = GuangGuUtil.getCardEvaluateUrl(cardEvaluateSendSmsVo);
			if (jsonObject == null) {
				return AjaxResult.error(3, "获取卡测评失败，请重试！");
			}
			String resCode = jsonObject.getString("res_code");
			if (("YQB000000").equals(resCode)) {
				String url = jsonObject.getString("url");
				order.setAcqReturnMsg(url);
				order.setAcqReturnCode("00");
				paymentOrderMapper.updatePaymentOrder(order);
				return AjaxResult.successAndData("成功", url);
			} else {
				order.setAcqReturnMsg("");
				order.setAcqReturnCode("11");
				LOGGER.error("【卡测评获取地址】{}", jsonObject.getString("res_msg"));
				return AjaxResult.error(1, jsonObject.getString("res_msg"));
			}
		} catch (Exception e) {
			LOGGER.error("【卡测评获取地址异常】{}", e);
			return AjaxResult.error(1, "卡测评获取地址异常");
		}
	}

	@Override
	public AjaxResult getHistoryList(String merId,Integer page) {
		// TODO Auto-generated method stub
		List<PaymentOrder> ol=paymentOrderMapper.selectCardEvaluateHistoryList(merId,page*2);
		List<CardEvaluateVo> li=new ArrayList<CardEvaluateVo>();
		Calendar calendarNow = Calendar.getInstance();
        calendarNow.setTime(new Date());
        int m1 = calendarNow.get(Calendar.MONTH);
		for (PaymentOrder paymentOrder : ol) {
			Calendar calendar = Calendar.getInstance();
	        calendar.setTime(paymentOrder.getCreateTime());
	        int m2 = calendar.get(Calendar.MONTH);
			CardEvaluateVo v= new CardEvaluateVo();
			v.setBankCardNo(paymentOrder.getCreditNumber());
			v.setMoney(paymentOrder.getAmountMoney());
			v.setName(paymentOrder.getMerchantName());
			v.setTime(paymentOrder.getCreateTime());
			v.setUrl(paymentOrder.getAcqReturnMsg());
			if(m1>m2){
				v.setStatus(1);
			}else{
				v.setStatus(0);
			}
			v.setSeriaNo(paymentOrder.getOrderNo());
			li.add(v);
		}
		return AjaxResult.successAndData("成功", li);
	}

}
